package xxx

import (
	"fmt"
	"iter"
	"slices"

	shs "gitee.com/asphodelus_dev/simple-hashtable-storage"
)

type KVPair struct {
	Key   []byte
	Value uint64
}

type LinkedListDataIndex LinkedList[KVPair]

var _ shs.Index = (*LinkedListDataIndex)(nil)

func (l *LinkedListDataIndex) Get(key []byte) (uint64, error) {
	nd := l.head
	for nd != nil {
		if slices.Equal(nd.value.Key, key) {
			return nd.value.Value, nil
		}
		nd = nd.next
	}
	return 0, fmt.Errorf("key not found")
}

func (l *LinkedListDataIndex) Set(key []byte, value uint64) error {
	(*LinkedList[KVPair])(l).PushFront(KVPair{Key: key, Value: value})
	return nil
}

func (l *LinkedListDataIndex) Delete(key []byte) error {
	var prev *node[KVPair]
	current := l.head

	for current != nil {
		if !slices.Equal(current.value.Key, key) {
			prev = current
			current = current.next
			continue
		}

		if prev == nil {
			// 如果是要删除头节点
			l.head = current.next
		} else {
			prev.next = current.next
		}
		return nil
	}
	return nil
}

func (l *LinkedListDataIndex) Iterator() iter.Seq2[[]byte, uint64] {
	return func(yield func([]byte, uint64) bool) {
		current := l.head
		for current != nil {
			if !yield(current.value.Key, current.value.Value) {
				return
			}
			current = current.next
		}
	}
}
